const axios = require('axios');
const cheerio = require('cheerio');
const { URL } = require('url');
const Audit = require('../models/Audit');
const Site = require('../models/Site');
const ErrorResponse = require('../utils/errorResponse');

// @desc    创建网站审核
// @route   POST /api/audits
// @access  Private
const createAudit = async (req, res) => {
  try {
    const { siteId, auditType } = req.body;
    const userId = req.user.id;

    // 检查网站是否存在
    const site = await Site.findById(siteId);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权审核此网站' 
      });
    }

    // 创建审核记录
    const newAudit = await Audit.create({
      user: userId,
      site: siteId,
      auditType: auditType || 'full'
    });

    // 启动审核过程（异步）
    performAudit(newAudit);

    res.status(201).json({
      status: 'success',
      data: newAudit
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取用户所有审核记录
// @route   GET /api/audits
// @access  Private
const getAudits = async (req, res) => {
  try {
    const audits = await Audit.find({ user: req.user.id })
      .populate('site', 'name url');
    
    res.status(200).json({
      status: 'success',
      data: audits
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取审核详情
// @route   GET /api/audits/:id
// @access  Private
const getAuditDetails = async (req, res) => {
  try {
    const { id } = req.params;

    const audit = await Audit.findById(id).populate('site', 'name url');
    if (!audit) {
      return res.status(404).json({ 
        status: 'error', 
        message: '审核记录不存在' 
      });
    }

    // 确保用户拥有该审核记录
    if (audit.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权访问此审核记录' 
      });
    }

    res.status(200).json({
      status: 'success',
      data: audit
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    运行完整网站审核
// @route   POST /api/audits/full-audit
// @access  Private
const runFullAudit = async (req, res) => {
  try {
    const { siteId } = req.body;
    const userId = req.user.id;

    // 检查网站是否存在
    const site = await Site.findById(siteId);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权审核此网站' 
      });
    }

    // 创建审核记录
    const newAudit = await Audit.create({
      user: userId,
      site: siteId,
      auditType: 'full',
      status: 'in-progress'
    });

    // 执行完整审核
    const auditResult = await performFullAudit(siteId);

    // 更新审核记录
    newAudit.status = 'completed';
    newAudit.result = auditResult;
    await newAudit.save();

    res.status(200).json({
      status: 'success',
      data: newAudit
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// 执行审核的辅助函数
const performAudit = async (audit) => {
  try {
    // 模拟审核过程
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    // 更新审核状态
    audit.status = 'completed';
    audit.result = generateAuditResult(audit.auditType);
    audit.updatedAt = new Date();
  } catch (error) {
    audit.status = 'failed';
    audit.error = error.message;
    audit.updatedAt = new Date();
  }
};

// 执行完整网站审核的辅助函数
const performFullAudit = async (siteId) => {
  // 在实际应用中，这里应该从数据库获取网站URL
  const siteUrl = 'https://example.com'; // 模拟网站URL
  
  try {
    // 1. 获取网站HTML内容
    const response = await axios.get(siteUrl);
    const html = response.data;
    const $ = cheerio.load(html);

    // 2. 执行各种SEO检查
    const seoChecks = performSeoChecks($, siteUrl);
    const performanceChecks = performPerformanceChecks(html);
    const securityChecks = performSecurityChecks(response.headers);
    const accessibilityChecks = performAccessibilityChecks($);

    return {
      siteUrl,
      timestamp: new Date(),
      seoChecks,
      performanceChecks,
      securityChecks,
      accessibilityChecks,
      overallScore: calculateOverallScore(
        seoChecks,
        performanceChecks,
        securityChecks,
        accessibilityChecks
      )
    };
  } catch (error) {
    throw new Error(`网站审核失败: ${error.message}`);
  }
};

// 执行SEO检查的辅助函数
const performSeoChecks = ($, url) => {
  const title = $('title').text();
  const metaDescription = $('meta[name="description"]').attr('content');
  const h1Tags = [];
  $('h1').each((i, el) => {
    h1Tags.push($(el).text());
  });

  // 检查图片alt属性
  const imagesWithoutAlt = [];
  $('img').each((i, el) => {
    if (!$(el).attr('alt')) {
      imagesWithoutAlt.push($(el).attr('src'));
    }
  });

  // 检查结构化数据
  const structuredData = $('script[type="application/ld+json"]').length;

  // 检查规范标签
  const canonicalTag = $('link[rel="canonical"]').attr('href');

  // 检查robots meta标签
  const robotsMeta = $('meta[name="robots"]').attr('content');

  return {
    basicSeo: {
      hasTitle: !!title,
      titleLength: title ? title.length : 0,
      hasMetaDescription: !!metaDescription,
      metaDescriptionLength: metaDescription ? metaDescription.length : 0,
      h1Count: h1Tags.length,
      multipleH1: h1Tags.length > 1
    },
    images: {
      totalImages: $('img').length,
      imagesWithoutAlt: imagesWithoutAlt.length,
      examplesWithoutAlt: imagesWithoutAlt.slice(0, 3)
    },
    links: {
      internalLinks: $('a[href^="/"], a[href^="' + url + '"]').length,
      externalLinks: $('a[href^="http"]').not(`a[href^="${url}"]`).length,
      nofollowLinks: $('a[rel="nofollow"]').length,
      brokenLinks: 0 // 在实际应用中应该检查
    },
    structuredData: {
      hasData: structuredData > 0,
      count: structuredData
    },
    canonicalization: {
      hasCanonical: !!canonicalTag,
      correctCanonical: canonicalTag === url
    },
    indexing: {
      robotsMeta: robotsMeta || 'none',
      noindex: robotsMeta && robotsMeta.includes('noindex')
    }
  };
};

// 执行性能检查的辅助函数
const performPerformanceChecks = (html) => {
  const pageSize = Buffer.byteLength(html, 'utf8') / 1024; // KB

  return {
    pageSize,
    score: Math.min(100, Math.floor(100 - pageSize / 10)), // 模拟分数
    recommendations: [
      pageSize > 500 ? '优化图片大小' : null,
      '启用浏览器缓存',
      '最小化CSS和JavaScript'
    ].filter(Boolean)
  };
};

// 执行安全检查的辅助函数
const performSecurityChecks = (headers) => {
  return {
    https: headers['strict-transport-security'] ? true : false,
    xssProtection: headers['x-xss-protection'] ? true : false,
    contentTypeOptions: headers['x-content-type-options'] === 'nosniff',
    frameOptions: headers['x-frame-options'] ? true : false,
    score: Math.floor(Math.random() * 40) + 60 // 模拟分数
  };
};

// 执行可访问性检查的辅助函数
const performAccessibilityChecks = ($) => {
  const contrastIssues = [];
  $('*').each((i, el) => {
    // 在实际应用中应该检查颜色对比度
    if (Math.random() > 0.9) {
      contrastIssues.push({
        element: el.name,
        text: $(el).text().slice(0, 50)
      });
    }
  });

  return {
    ariaAttributes: $('[aria-*]').length,
    contrastIssues: contrastIssues.length,
    score: Math.floor(Math.random() * 30) + 70, // 模拟分数
    issues: contrastIssues.slice(0, 5)
  };
};

// 计算总体分数的辅助函数
const calculateOverallScore = (seo, performance, security, accessibility) => {
  return Math.floor(
    (seo.basicSeo.hasTitle ? 10 : 0) +
    (seo.basicSeo.hasMetaDescription ? 10 : 0) +
    (seo.images.imagesWithoutAlt === 0 ? 10 : 5) +
    (performance.score * 0.3) +
    (security.score * 0.2) +
    (accessibility.score * 0.2)
  );
};

// 生成审核结果的辅助函数
const generateAuditResult = (auditType) => {
  const result = {
    timestamp: new Date(),
    overallScore: Math.floor(Math.random() * 40) + 60,
    issues: []
  };

  // 根据审核类型添加特定问题
  if (auditType === 'full' || auditType === 'seo') {
    result.seoIssues = [
      { issue: '缺少meta描述', severity: 'medium' },
      { issue: '图片缺少alt属性', severity: 'high' },
      { issue: '多个H1标签', severity: 'low' }
    ].slice(0, Math.floor(Math.random() * 3) + 1);
  }

  if (auditType === 'full' || auditType === 'performance') {
    result.performanceIssues = [
      { issue: '页面大小过大', severity: 'medium' },
      { issue: '未启用浏览器缓存', severity: 'high' },
      { issue: '未压缩的JavaScript', severity: 'low' }
    ].slice(0, Math.floor(Math.random() * 3) + 1);
  }

  if (auditType === 'full' || auditType === 'security') {
    result.securityIssues = [
      { issue: '缺少HSTS头', severity: 'high' },
      { issue: '缺少X-XSS-Protection头', severity: 'medium' },
      { issue: '缺少Content-Security-Policy', severity: 'high' }
    ].slice(0, Math.floor(Math.random() * 3) + 1);
  }

  return result;
};

module.exports = {
  createAudit,
  getAudits,
  getAuditDetails,
  runFullAudit
};